package com.app.mvvmkotlindemo

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.app.mvvmkotlindemo.event.EventViewModel
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.everyline.baselibrary.ext.getAppViewModel
import com.everyline.baselibrary.utils.DateTimeUtils
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Function
import okhttp3.RequestBody
import java.util.*

class MainActivity : AppCompatActivity() {

//    const val jsonType = "application/json; charset=utf-8"
//    const val fileType = "text/x-markdown; charset=utf-8"








    //Application全局的ViewModel，用于发送全局通知操作
    val eventViewModel: EventViewModel by lazy { getAppViewModel<EventViewModel>() }











    private var pvOptions1: OptionsPickerView<*>? = null
    private var pvOptions2: OptionsPickerView<*>? = null
    private var pvOptionsAreaBank: OptionsPickerView<*>? = null
    private var pvOptionsCarColor: OptionsPickerView<*>? = null
    private var pvOptionsBank: OptionsPickerView<*>? = null
    private var pvTimeidentityBegin: TimePickerView? = null
    private var pvTimeidentityEnd: TimePickerView? = null
    private var pvTimedriverCardPicA: TimePickerView? = null
    private var pvTimedriverCardPicB: TimePickerView? = null
    private var pvTimecdStartDate: TimePickerView? = null
    private var pvTimecdExpire: TimePickerView? = null
    private var pvTimevehicleCardStartDate: TimePickerView? = null
    private var pvTimevehicleCardExpire: TimePickerView? = null
    private var pvTimeOpCertExpire: TimePickerView? = null
    private var pvTimeCinsExpire: TimePickerView? = null
    private var pvTimeRinsExpire: TimePickerView? = null
    private var pvTimeBinsExpire: TimePickerView? = null










    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    //保单信息承运险有效期

    private var selectcinsExpire: Calendar? = null

//    fun initpvTimeCinsExpirePicker() {
//
//        selectcinsExpire = Calendar.getInstance()
//
//        pvTimeCinsExpire?.let {
//            if (it.isShowing) {
//                return@let
//            }
//        }
//
//        if (StringUtils.isEmpty(cinsExpire)) {
//
//
//            val beginTime =
//                TimeUtils.date2String(Date(System.currentTimeMillis()), "yyyy-MM-dd")
//            val selecteTime = beginTime.split("-").toTypedArray()
//
//
//            selectcinsExpire!![Calendar.YEAR] = Integer.valueOf(selecteTime[0])
//            selectcinsExpire!![Calendar.MONTH] = Integer.valueOf(selecteTime[1]) - 1
//            selectcinsExpire!![Calendar.DAY_OF_MONTH] = Integer.valueOf(selecteTime[2])
//        } else {
//
//            val selecteTime = cinsExpire!!.split("-").toTypedArray()
//
//
//            selectcinsExpire!![Calendar.YEAR] = Integer.valueOf(selecteTime[0])
//            selectcinsExpire!![Calendar.MONTH] = Integer.valueOf(selecteTime[1]) - 1
//            selectcinsExpire!![Calendar.DAY_OF_MONTH] = Integer.valueOf(selecteTime[2])
//        }
//
//        //今天的时间
//        val startDate = Calendar.getInstance()
//        startDate.set(1950, 1, 1)
//
//        val endDate = Calendar.getInstance()
//
//        endDate.set(2050, 12, 31)
//
//        pvTimeCinsExpire = TimePickerBuilder(this, object : OnTimeSelectListener {
//            override fun onTimeSelect(date: Date?, v: View?) {
//                DateTimeUtils.getTimeYMD(date!!)
//                LogUtils.d("date==============${DateTimeUtils.getTimeYMD(date)}")
//
//                cinsExpire = "${DateTimeUtils.getTimeYMD(date)}"
//                mDatabind.layoutDataUploadPicBaodanInfo.tvCinsExpire.text =
//                    "$cinsExpire"
//
//
//
//
//                compareToCinsExpire()
//
//
//                initCheckBaodan()
//
//
//            }
//
//        })
//            .setDate(startDate)
//            .setRangDate(startDate, endDate)
//            .setLayoutRes(
//                R.layout.layout_data_upload_date_dialog
//            ) { v ->
//                val tv_ok = v.findViewById<TextView>(R.id.tv_ok);
//                val tv_name = v.findViewById<TextView>(R.id.tv_name);
//                tv_name.text = "承运险有效期"
//
//                tv_ok.setOnClickListener {
//                    pvTimeCinsExpire?.returnData()
//                    pvTimeCinsExpire?.dismiss()
//                }
//
//            }
//            .isDialog(false)//是否显示为对话框样式
//            .setItemVisibleCount(3)
//            .setOutSideCancelable(true)
//            .setBgColor(Color.WHITE)
//            .setRangDate(startDate, endDate)
//            .setDate(selectcinsExpire)
//            .setType(booleanArrayOf(true, true, true, false, false, false))
//            .setLabel("年", "月", "日", "时", "分", "秒")
//            .setDecorView(window.decorView.findViewById(android.R.id.content))
//            .build()
//
//        pvTimeCinsExpire?.show()
//
//    }
//
//
//    private fun initOptionPicker() {
//
//        if (pvOptions1 != null) {
//            pvOptions1!!.show()
//        } else {
//
//
//            pvOptions1 = OptionsPickerBuilder(
//                this
//            ) { options1, option2, options3, v ->
//
//                localProvince = provinceList[options1].provinceName
//                localCity = cityList[options1][option2]
//
//
//                localProvinceId = "${provinceList[options1].provinceId}"
//                localCityId = "${cityListData[options1][option2].cityId}"
//
//                if (oldcityId == localCityId) {
//
//
//                } else {//当选择的不一样的时候清空原先的数据
//                    oldProvinceId == localProvinceId
//                    oldcityId = localCityId!!
//                    departmentId = ""
//                    mDatabind.layoutDataUploadPicYunyingInfo.tvOperator.text = ""
//                    openAreaBeanList.clear()
//
//                }
//                LogUtils.d("provinceId==${localProvinceId}==cityId==${localCityId} ==oldProvinceId==${oldProvinceId}===oldcityId==${oldcityId}")
//
//                mDatabind.layoutDataUploadPicYunyingInfo.tvCity.text =
//                    "${localProvince}-${localCity}"
//                mDatabind.layoutDataUploadPicYunyingInfo.llOperator.visibility = View.VISIBLE
//
//                findAllZcDepartmentByOpenArea()
//
//
//                initCheckYunYing()
//            }
//                .setLayoutRes(R.layout.layout_city_dialog) { v -> //自定义布局中的控件初始化及事件处理
//                    val tv_ok = v.findViewById<TextView>(R.id.tv_ok);
//                    val tv_name = v.findViewById<TextView>(R.id.tv_name);
//                    tv_name.text = "运营城市"
//
//                    tv_ok.setOnClickListener {
//                        pvOptions1?.returnData()
//                        pvOptions1?.dismiss()
//                    }
//
//                }
//                .isDialog(false)//是否显示为对话框样式
//                .setSelectOptions(0, 0)//默认选中项
//                .setItemVisibleCount(5)
//                .setLabels("", "", "")
//                .setOutSideCancelable(true)
//                .addOnCancelClickListener {
//                    LogUtils.d("取消了============")
//                }
//
//                .setDecorView(
//                    getWindow().getDecorView().findViewById(android.R.id.content) as ViewGroup
//                )
//                .build<Any>()
//
//            (pvOptions1 as OptionsPickerView<Any>?)?.setPicker(
//                provinceList as List<Any>?,
//                cityList as List<MutableList<Any>>?,
//                null
//            )
//            pvOptions1!!.show()
//        }
//    }



//    waitDriverArriveDisposable = Observable.interval(0, 1, TimeUnit.SECONDS)
//    .subscribeOn(Schedulers.io())
//    .observeOn(AndroidSchedulers.mainThread(), true)
//    .subscribe({
//        timestampArriveTime += (1 * 1000).toLong()
//
//        if (timestampArriveTime < arriveWaitTime) {
//
//            val day = String.format("%02d", timestampArriveTime / (1000 * 60 * 60 * 24))
//            val hour = String.format(
//                "%02d",
//                timestampArriveTime % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)
//            )
//            val minute =
//                String.format("%02d", timestampArriveTime % (1000 * 60 * 60) / (1000 * 60))
//            val second = String.format("%02d", timestampArriveTime % (1000 * 60) / 1000)
//            driverArriveTime = "$minute:$second"
//            LogUtils.d(
//                "hour333333===",
//                "day====$day===hour====$hour===minute==$minute===second==$second===formatTime==$driverArriveTime"
//            )
//
//        }
//
//        markerStart!!.showInfoWindow()
//    }) {
//        LogUtils.d("${it}")
//    }

//    private fun createMarker(latLng: LatLng, title: String, icon: Int): MarkerOptions {
//        val view = layoutInflater.inflate(R.layout.layout_call_car_details_info_window, null)
//        view.findViewById<TextView>(R.id.call_car_detais_infowindow_title).text = title
//        view.findViewById<ImageView>(R.id.iv_icon)
//            .setBackgroundResource(icon)
//
//        val markIcon = BitmapDescriptorFactory.fromView(view)
//        return MarkerOptions().position(latLng).icon(markIcon)
//    }



//    val filePath = OcrFileUtils.getSaveFile(
//        applicationContext,
//        risk_carrier_png!!
//    ).absolutePath
//    LogUtils.d("承运险图片路径=====${filePath}")
//
//
//    val partMap: MutableMap<String, RequestBody> = HashMap()
//    val file = File(filePath)
//    partMap["plate"] =
//    "8".toRequestBody(Constants.jsonType.toMediaType())
//    partMap["file\"; filename=\"" + file.name] =
//    file.asRequestBody(Constants.fileType.toMediaType())
//
//    requestDataUploadModel.uploadcinsPic(partMap)




//
//    private fun initCheckDriverTextViewOREditetext() {
//
//        val observableDriverName: Observable<CharSequence> =
//            mDatabind.layoutDataUploadPicDriveInfo.etDriverName.textChanges()
//        val observableIdCard: Observable<CharSequence> =
//            mDatabind.layoutDataUploadPicDriveInfo.etIdCard.textChanges()
//        Observable.combineLatest(
//            observableDriverName,
//            observableIdCard,
//            object : Function2<kotlin.CharSequence, kotlin.CharSequence, Boolean> {
//
//                override fun invoke(p1: kotlin.CharSequence, p2: kotlin.CharSequence): Boolean {
//                    return !StringUtils.isEmpty(mDatabind.layoutDataUploadPicDriveInfo.etDriverName.text) && !StringUtils.isEmpty(
//                        mDatabind.layoutDataUploadPicDriveInfo.etIdCard.text
//                    )
//
//                }
//
//            }).subscribe {
//            initCheckDriver()
//        }
//
//
//    }
//
//    private fun initCheckCarTextViewOREditetext() {
//        val observableVin: Observable<CharSequence> =
//            mDatabind.layoutDataUploadPicCarInfo.etVin.textChanges()
//        observableVin.map(object : Function<CharSequence, Boolean> {
//            override fun apply(t: CharSequence?): Boolean {
//                return !StringUtils.isEmpty(mDatabind.layoutDataUploadPicCarInfo.etVin.text)
//            }
//
//        }).subscribe {
//            initCheckCar()
//        }
//
//    }



    private var currentTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (System.currentTimeMillis() - currentTime > 2000) {
                currentTime = System.currentTimeMillis()
                ToastUtils.showShort("再按一次退出程序")
            } else {
                finish()
            }
            return true


        }

        return super.onKeyDown(keyCode, event)
    }
}